package cn.szzsi.service;

import cn.szzsi.common.bean.CartItemCookie;
import cn.szzsi.common.model.Member;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * Created by admin on 2017/3/22.
 */
public class LoginService {


    /**
     *
     * @param request
     * @param user ({"GUID":"0400c08dc9f84bb9b48525ff0a706c10","USER_NAME":"zheng","SHOP_ID":"0"})
     */
    public static void loginSuccess(HttpServletRequest request, HttpServletResponse response, JSONObject user, String code){
        System.out.println(user);
        String mid=user.get("GUID").toString();//用户ID
        String username=user.get("USER_NAME").toString();//应户名
        String shopId=user.get("SHOP_ID").toString();//店铺ID
        request.getSession().setAttribute(Member.LOGIN_MEMBER_ID_SESSION_NAME,mid);

        // 写入会员登录Session
        request.getSession().setAttribute(Member.LOGIN_MEMBER_ID_SESSION_NAME, mid);

        // 写入会员登录Cookie和登录类型Cookie
        Cookie loginMemberUsernameCookie = null;
        Cookie loginTypeCookie = null;
        try {
            loginMemberUsernameCookie = new Cookie(Member.LOGIN_MEMBER_USERNAME_COOKIE_NAME, URLEncoder.encode(username.toLowerCase(), "UTF-8"));//用户名
            loginTypeCookie=new Cookie(Member.LOGIN_TYPE_COOKIE_NAME,"business");//登录类型
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        loginMemberUsernameCookie.setPath(request.getContextPath() + "/");
        loginTypeCookie.setPath(request.getContextPath()+"/");
        response.addCookie(loginMemberUsernameCookie);
        response.addCookie(loginTypeCookie);

        // 清空临时购物车Cookie
        Cookie cartItemCookie = new Cookie(CartItemCookie.CART_ITEM_LIST_COOKIE_NAME, null);
        cartItemCookie.setPath(request.getContextPath() + "/");
        cartItemCookie.setMaxAge(0);
        response.addCookie(cartItemCookie);

        request.getSession().removeAttribute(Member.LOGIN_REDIRECTION_URL_SESSION_NAME);
        try {
            response.sendRedirect("/memberCenter/"+code);//重定向
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
